const http = require("../../api/second")
import dayjs from 'dayjs';
// const dayjs = require("../../node_modules/dayjs")
const {
  baseURL
} = require("../../utils/request")

Page({
  /**
   * 页面的初始数据
   */
  data: {
    dynamicList: [],
    _dynamicList: [],
    selectText: "",
    option: [{
        text: '默认排序',
        value: 1
      },
      {
        text: '热度↑',
        value: 2
      },
      {
        text: '热度↓',
        value: 3
      },
      {
        text: '发布时间由新到旧',
        value: 4
      },
      {
        text: '发布时间由旧到新',
        value: 5
      },
    ],
    value: 1,
    sortModel: "",
    userId: wx.getStorageSync('userInfo').userId,
    username: wx.getStorageSync('userInfo').username,
    addDialogShow: false,
    images: [],
    fileList: [],
    imageUrl: "",
    textContent: "",
    detailShow: false,
    index: "",
    addCommonsShow: false,
    commentsText: "",
    addDynamicId:"",

  },
  commentsAdd(){

    http.commentsAdd({
      dynamicId:this.data.addDynamicId,
      userId:this.data.userId,
      commentsText:this.data.commentsText,
      username:this.data.username,
    }).then(res=>{
      if(res.code == 200){
        wx.showToast({
          title: '插嘴成功',
        })
        this.setData({
          addCommonsShow: false,
          commentsText: "",
        })
        this.initDynamicList()
      }
    })
  },
  changeCommentsText(e) {
    this.setData({
      commentsText: e.detail.value
    })
    
  },
  onOpenAddCommonts(e) {
    this.setData({
      addCommonsShow: true,
      addDynamicId:e.currentTarget.dataset.dymid
    })
  },
  onCloseAddCommonts() {
    this.setData({
      addCommonsShow: false,
      commentsText:""
    })
  },
  onClickImg(e) {
    console.log("点击图片事件", e);
    var imageUrl = "http://127.0.0.1:8080" + e.currentTarget.dataset.imageurl
    wx.previewImage({
      urls: [imageUrl], //需要预览的图片http链接列表，注意是数组
      current: '', // 当前显示图片的http链接，默认是第一个
      success: function (res) {},
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  openDetail(event) {
    console.log("event", event);
    this.setData({
      index: event.currentTarget.dataset.index,
      detailShow: true

    })

  },
  closeDetail() {
    this.setData({
      detailShow: false
    })
  },
  changeText(e) {
    this.setData({
      textContent: e.detail.value
    })
  },
  afterRead(event) {
    console.log("event", event);
    var that = this;
    const {
      file
    } = event.detail;
    const userInfo = wx.getStorageSync('userInfo') || null;
    const token = userInfo.token
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: 'http://127.0.0.1:8080/common/upload', // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: 'file',
      formData: {
        user: 'test'
      },
      header: {
        'Authorization': `Bearer ${token}`,
        'content-type': 'application/json',
      },
      success(res) {
        // 上传完成需要更新 fileList
        const {
          fileList = []
        } = that.data;
        const {
          images = []
        } = that.data;
        var resData = JSON.parse(res.data)
        console.log("images res", res)
        console.log("images resData", resData)
        images.push({
          ...file,
          imageUrl: resData.fileName
        });
        fileList.push({
          ...file,
          url: resData.fileName
        });
        that.setData({
          images
        });
        that.setData({
          fileList
        });
        console.log("fileList", that.data.fileList)
        console.log("images", that.data.images)
      },
    });
  },

  showExchanges() {
    this.setData({
      addDialogShow: true
    })
  },
  onCloseExchanges() {
    this.setData({
      addDialogShow: false,
      textContent: "",
      images: [],
      fileList: [],
    })
  },
  // 选择筛选方式触发
  onSelectChange() {
    this.sort()
  },
  // 搜索
  onSearch(event) {
    const filteredArray = this.data._dynamicList.filter(item =>
      item.textContent.toLowerCase().includes(event.detail.toLowerCase()) ||
      item.userInfo.username.toLowerCase().includes(event.detail.toLowerCase())
    );
    this.setData({
      dynamicList: filteredArray
    })
  },

  // 查询用户发布的动态
  initDynamicList() {
    http.dynamicList().then((res) => {
      if (res.code == 200) {
        const dynamicData = res.rows.map(dynamic => {
          dynamic.createTime = dayjs(dynamic.createTime).format('YYYY年MM月DD日 HH:mm');
          dynamic.comments = dynamic.comments.map(comment => {
            comment.createTime = dayjs(comment.createTime).format('YYYY-MM-DD HH:mm');
            return comment;
          });
      
          return dynamic; // 返回动态对象
        });
        this.setData({
          dynamicList: dynamicData,
          _dynamicList: dynamicData
        })
      }
    });
  },
  // 排序函数
  sort() {
    let sortedArray = []
    if (this.data.value == 1) {
      sortedArray = this.data._dynamicList
    } else if (this.data.value == 2) {
      sortedArray = this.data._dynamicList.sort((a, b) => a.comments.length - b.comments.length);
    } else if (this.data.value == 3) {
      sortedArray = this.data._dynamicList.sort((a, b) => b.comments.length - a.comments.length);
    } else if (this.data.value == 4) {
      sortedArray = this.data._dynamicList.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
    } else if (this.data.value == 5) {
      sortedArray = this.data._dynamicList.sort((a, b) => new Date(a.createTime) - new Date(b.createTime));
    }
    this.setData({
      dynamicList: sortedArray
    })
  },
  addExchanges() {
    http.dynamicAdd({
      userId: this.data.userId,
      textContent: this.data.textContent,
      images: this.data.images
    }).then(res => {
      if (res.code == 200) {
        wx.showToast({
          title: '发布成功',
        })
        this.onCloseExchanges(),

          this.initDynamicList()
      }
    })
  },

  // 根据热度排序

  // 根据发布时间排序

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.initDynamicList()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})